using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace demo
{
    /// <summary>
    /// 简单的IME辅助工具：保存/设置/恢复窗口句柄对应的输入法状态（半角英文）。
    /// 说明：依赖imm32.dll，仅影响当前进程线程关联的输入上下文，不会影响其他程序。
    /// </summary>
    public static class ImeHelper
    {
        // Win32 IME API
        [DllImport("imm32.dll")]
        private static extern IntPtr ImmGetContext(IntPtr hWnd);

        [DllImport("imm32.dll")]
        private static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);

        [DllImport("imm32.dll")]
        private static extern bool ImmGetConversionStatus(IntPtr hIMC, out uint lpfdwConversion, out uint lpfdwSentence);

        [DllImport("imm32.dll")]
        private static extern bool ImmSetConversionStatus(IntPtr hIMC, uint fdwConversion, uint fdwSentence);

        [DllImport("imm32.dll")]
        private static extern bool ImmGetOpenStatus(IntPtr hIMC);

        [DllImport("imm32.dll")]
        private static extern bool ImmSetOpenStatus(IntPtr hIMC, bool fOpen);

        // 常用转换标志（部分）
        private const uint IME_CMODE_ALPHANUMERIC = 0x0000;    // 英数
        private const uint IME_CMODE_FULLSHAPE = 0x0008;       // 全角

        /// <summary>
        /// 读取当前窗口的IME打开状态与转换/造句模式。
        /// </summary>
        public static bool TryGetImeStatus(IntPtr hwnd, out bool isOpen, out uint conversion, out uint sentence)
        {
            isOpen = false;
            conversion = 0;
            sentence = 0;

            try
            {
                if (hwnd == IntPtr.Zero) return false;
                IntPtr hIMC = ImmGetContext(hwnd);
                if (hIMC == IntPtr.Zero) return false;

                isOpen = ImmGetOpenStatus(hIMC);
                bool ok = ImmGetConversionStatus(hIMC, out conversion, out sentence);
                ImmReleaseContext(hwnd, hIMC);
                return ok;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 将IME设置为半角英文/数字模式（清除全角，使用英数）。
        /// </summary>
        public static bool TrySetHalfWidthEnglish(IntPtr hwnd)
        {
            try
            {
                if (hwnd == IntPtr.Zero) return false;
                IntPtr hIMC = ImmGetContext(hwnd);
                if (hIMC == IntPtr.Zero) return false;

                // 打开IME，再设置转换状态为英数（0），并确保非全角
                ImmSetOpenStatus(hIMC, true);
                // 造句模式保持默认（传入0即可由IME决定默认）；如果想严格保留，可先取再传回
                uint sentence = 0;
                ImmGetConversionStatus(hIMC, out var conv, out sentence);
                // 直接设置为英数（这会取消Native/中文及其他转换），并确保不包含全角
                uint newConv = IME_CMODE_ALPHANUMERIC;
                ImmSetConversionStatus(hIMC, newConv, sentence);
                ImmReleaseContext(hwnd, hIMC);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 恢复之前保存的IME打开状态与转换/造句模式。
        /// </summary>
        public static bool TryRestoreImeStatus(IntPtr hwnd, bool isOpen, uint conversion, uint sentence)
        {
            try
            {
                if (hwnd == IntPtr.Zero) return false;
                IntPtr hIMC = ImmGetContext(hwnd);
                if (hIMC == IntPtr.Zero) return false;
                ImmSetOpenStatus(hIMC, isOpen);
                ImmSetConversionStatus(hIMC, conversion, sentence);
                ImmReleaseContext(hwnd, hIMC);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}